<template>
  <div class="app-container">
    <vxe-grid
      id="gridRef"
      ref="gridRef"
      v-bind="gridOptions"
      @cell-dblclick="cellDblclickEvent"
      @scroll-boundary="scrollBoundaryEvent"
      @toolbar-button-click="toolbarButtonClickEvent"
    >
      <template #action="{ row }">
        <vxe-link
          v-for="(item, index) in actionButtonsMerge"
          :key="index"
          :class="item.class"
          :icon="item.icon"
          :status="item.status"
          @click="executeMethod(item.act, row)"
        >
          {{ item.name }}
        </vxe-link>
      </template>
      <template #userId="{ row }">
        <vxe-tag v-if="row.user_id" status="success">
          {{ (row.user && row.user.name) || row.user_id }}
        </vxe-tag>
        <vxe-tag v-else status="error">系统发布</vxe-tag>
      </template>
    </vxe-grid>
    <vxe-drawer
      v-model="showEditPopup"
      :confirm-closable="false"
      destroy-on-close
      :loading="loading"
      mask-closable
      show-cancel-button
      show-confirm-button
      show-footer
      :title="selectRow ? '编辑' : '新增'"
      :width="width"
      @confirm="confirmEvent"
    >
      <vxe-form
        ref="formRef"
        class-name="vxe-form--wrapper-nobg"
        v-bind="formOptions"
      />
    </vxe-drawer>
  </div>
</template>

<script>
  import { VxeUI } from 'vxe-pc-ui'
  import XEUtils from 'xe-utils'
  import { removeEmptyField, convertArr2Obj } from '@/utils'
  import axios from 'axios'
  import { baseURL } from '@/config'
  import { mapGetters } from 'vuex'
  export default {
    props: {
      width: {
        type: String,
        default() {
          return '50vw'
        },
      },
      getList: {
        type: Function,
        default: () => {},
      },
      doAdd: {
        type: Function,
        default: () => {},
      },
      doEdit: {
        type: Function,
        default: () => {},
      },
      doMultiDelete: {
        type: Function,
        default: () => {},
      },
      defaultData: {
        type: Object,
        default: () => {
          return {}
        },
      },
      columns: {
        type: Array,
        default: () => {
          return []
        },
      },
      formItems: {
        type: Array,
        default: () => {
          return []
        },
      },
      formRules: {
        type: Object,
        default: () => {
          return {}
        },
      },
      searchObj: {
        type: Object,
        default: () => {
          return { items: [], collapseNode: false }
        },
      },
      actionObj: {
        type: Object,
        default() {
          return {
            mode: 'copy',
            buttons: [],
          }
        },
      },
      initParams: {
        type: Object,
        default() {
          return {}
        },
      },
    },
    data() {
      const actionButtons = [
        {
          name: '修改',
          icon: 'vxe-icon-edit',
          status: 'primary',
          class: 'mr12',
          act: 'editRow',
        },
        {
          name: '删除',
          icon: 'vxe-icon-delete',
          status: 'danger',
          class: 'mr12',
          act: 'deleteRow',
        },
      ]
      const formOptions = {
        titleWidth: 80,
        titleAlign: 'right',
        titleColon: true,
        data: XEUtils.clone(this.defaultData, true),
        rules: this.formRules,
        items: this.formItems,
      }
      const gridOptions = {
        size: 'small',
        align: 'center',
        border: true,
        height: this.getHeight(),
        stripe: true,
        showOverflow: true,
        showHeaderOverflow: true,
        treeConfig: {
          rowField: 'id',
          childrenField: 'children',
        },
        formConfig: {
          size: 'small',
          items: this.searchObj.items.concat([
            {
              span: 4,
              align: 'left',
              collapseNode: this.searchObj.collapseNode,
              itemRender: {
                name: 'VxeButtonGroup',
                options: [
                  {
                    type: 'submit',

                    content: '搜索',
                    status: 'primary',
                  },
                  { type: 'reset', content: '重置' },
                ],
              },
            },
          ]),
        },
        columnConfig: {
          useKey: true,
          drag: true,
          resizable: true,
        },
        pagerConfig: {
          total: 0,
          currentPage: 1,
          pageSize: 20,
          perfect: true,
          size: 'small',
        },
        printConfig: {},
        exportConfig: {
          modes: ['current', 'selected', 'all'],
          type: 'xlsx',
          sheetMethod(params) {
            const { worksheet } = params
            const argb = '111'
            worksheet.eachRow((excelRow, rowIndex) => {
              if (rowIndex <= 1) {
                excelRow.eachCell((excelCell) => {
                  // 填充单元格背景
                  excelCell.fill = {
                    type: 'pattern',
                    pattern: 'solid',
                    fgColor: {
                      argb: 'c5d9f1',
                    },
                  }
                })
              }
              excelRow.eachCell((excelCell) => {
                excelCell.width = 16
                excelRow.height = 24
                excelCell.font = {
                  name: 'Microsoft YaHei',
                  size: 10,
                  color: {
                    argb,
                  },
                }
                if (rowIndex <= 1) {
                  excelRow.height = 32
                  excelCell.font = {
                    name: 'Microsoft YaHei',
                    size: 12,
                    bold: true,
                    color: {
                      argb,
                    },
                  }
                  excelCell.fill = {
                    type: 'pattern',
                    pattern: 'solid',
                    fgColor: {
                      argb: 'c5d9f1',
                    },
                  }
                }
                // 设置单元格边框
                excelCell.border = {
                  top: {
                    style: 'thin',
                    color: {
                      argb,
                    },
                  },
                  left: {
                    style: 'thin',
                    color: {
                      argb,
                    },
                  },
                  bottom: {
                    style: 'thin',
                    color: {
                      argb,
                    },
                  },
                  right: {
                    style: 'thin',
                    color: {
                      argb,
                    },
                  },
                }
              })
            })
          },
        },
        toolbarConfig: {
          perfect: true,
          export: true,
          print: true,
          zoom: true,
          custom: true,
          refresh: true,
          size: 'small',
          buttons: [
            {
              name: '新增',
              code: 'add',
              status: 'primary',
              size: 'mini',
              icon: 'vxe-icon-add',
            },
            {
              name: '删除',
              code: 'delete',
              status: 'error',
              icon: 'vxe-icon-delete',
            },
          ],
        },
        customConfig: {
          immediate: true,
          storage: {
            visible: true,
            resizable: true,
            sort: true,
            fixed: true,
          },
        },
        proxyConfig: {
          form: true,
          ajax: {
            query: ({ page, form }) => {
              return this.getListAct(page.pageSize, page.currentPage, form)
            },
            queryAll: (page, form) => {
              return this.getListAct(page.pageSize, page.currentPage, form, 0)
            },
            delete: ({ body }) => {
              return this.doMultiDeleteAct(body.removeRecords)
            },
          },
        },
        columns: this.columns.map((val) => {
          if (val.slotObj) {
            if (val.slotObj.component === 'vxe-tag') {
              val.slots = {
                default: ({ row }) => {
                  const map = convertArr2Obj(val.slotObj.options, 'value')
                  const item = map[row.valid || row.status]
                  return (
                    <span>
                      <vxe-tag status={item.status}>{item.label}</vxe-tag>
                    </span>
                  )
                },
              }
            }
          }
          return val
        }),
        data: [],
      }
      return {
        actionButtons,
        loading: false,
        formOptions,
        gridOptions,
        showEditPopup: false,
        selectRow: undefined,
      }
    },
    computed: {
      ...mapGetters(['token']),
      actionButtonsMerge() {
        const mode = this.actionObj.mode || 'copy'
        if (mode === 'concat') {
          return this.actionButtons.concat(this.actionObj.buttons)
        }
        if (mode === 'replace') {
          return this.actionObj.buttons
        }
        return this.actionButtons
      },
    },
    methods: {
      uploadMethod({ file }, namekey, multi = false) {
        return new Promise((resolve, reject) => {
          const formData = new FormData()
          formData.append('file', file) // 确保文件字段名称正确

          // 设置请求头
          const headers = {
            'Content-Type': 'multipart/form-data',
            Authorization: `Bearer ${this.token}`,
          }

          axios
            .post(`${baseURL}/api/upload/image`, formData, {
              headers,
            })
            .then((res) => {
              if (res.status === 200) {
                let {
                  data: { path },
                } = res.data
                path = baseURL + path
                if (multi) {
                  this.formOptions.data[namekey].push(path)
                } else {
                  this.formOptions.data[namekey] = path
                }
              } else {
                reject(new Error('上传失败'))
              }
            })
            .catch((error) => {
              reject(error)
            })
        })
      },
      scrollBoundaryEvent() {
        console.log('ok')
      },
      getHeight() {
        return '720'
      },
      executeMethod(methodName, row) {
        if (typeof this[methodName] === 'function') {
          this[methodName](row)
        }
      },
      async getListAct(pageSize, currentPage, queryObj, pageable = 1) {
        let pageQuery = { page: currentPage, pagesize: pageSize }
        if (!pageable) {
          pageQuery = {}
        }
        if (this.initParams) {
          queryObj = { ...queryObj, ...this.initParams }
        }
        const query = removeEmptyField({ ...pageQuery, ...queryObj })
        const {
          data: { data, total },
        } = await this.getList(query)

        return new Promise((resolve) => {
          setTimeout(() => {
            resolve({
              result: data,
              page: {
                total,
              },
            })
          }, 100)
        })
      },
      async doMultiDeleteAct(rows) {
        await this.doMultiDelete(
          rows.map((item) => item.id || item.serialno)
        ).then((res) => {
          if (res.errorCode === 0) {
            VxeUI.modal.message({
              content: '成功删除所选记录',
              status: 'success',
            })
            return new Promise((resolve) => {
              setTimeout(() => {
                resolve()
                this.$refs.gridRef.commitProxy('reload')
              }, 150)
            })
          }
        })
      },
      async doAddAct(postData) {
        this.doAdd(postData).then((res) => {
          if (res.errorCode === 0) {
            VxeUI.modal.message({
              content: res.msg,
              status: 'success',
            })
            setTimeout(() => {
              this.$refs.gridRef.commitProxy('reload')
              this.showEditPopup = false
            }, 150)
          }
        })
      },
      async doEditAct(postData) {
        this.doEdit(postData.id, postData).then((res) => {
          if (res.errorCode === 0) {
            VxeUI.modal.message({
              content: res.msg,
              status: 'success',
            })
            setTimeout(() => {
              this.$refs.gridRef.commitProxy('reload')
              this.showEditPopup = false
            }, 150)
          }
        })
      },
      addEvent(row = null) {
        this.selectRow = undefined
        this.formOptions.data = XEUtils.clone(this.defaultData, true)
        if (row && row.id) {
          this.formOptions.data.pid = row.id
        }
        this.showEditPopup = true
      },
      deleteRow(row) {
        VxeUI.modal
          .confirm({
            title: '系统提示',
            content: '您确定要删除所选记录吗？',
          })
          .then((type) => {
            if (type === 'confirm') {
              const $grid = this.$refs.gridRef
              if ($grid) {
                this.doMultiDeleteAct([row])
              }
            }
          })
      },
      editRow(row) {
        this.selectRow = row
        this.formOptions.data = Object.assign(
          XEUtils.clone(this.defaultData, true),
          row
        )
        this.showEditPopup = true
      },
      async confirmEvent() {
        const $form = this.$refs.formRef
        if ($form) {
          const errMap = await $form.validate()
          if (!errMap) {
            const postData = this.formOptions.data
            delete postData._X_ROW_KEY
            if (postData.id) {
              this.doEditAct(postData)
            } else {
              this.doAddAct(postData)
            }
          }
        }
      },
      toolbarButtonClickEvent(params) {
        if (params.code === 'add') {
          this.addEvent()
        }
      },
      cellDblclickEvent: function ({ row, column }) {
        console.log(`双击行：${row.id} 双击列：${column.title}`)
      },
    },
  }
</script>

<style lang="scss" scoped></style>
